package com.cruise.game.common.config;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalTimeSerializer;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.annotation.Order;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;

import java.io.IOException;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.util.Locale;
import java.util.TimeZone;

/**
 * Jackson配置类
 *
 * @author cruise
 * @date 2025-03-01
 */
@Configuration
@Order(1) // 提高配置优先级
public class JacksonConfig {

    /**
     * 默认日期时间格式
     */
    private static final String DEFAULT_DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";

    /**
     * 默认日期格式
     */
    private static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd";

    /**
     * 默认时间格式
     */
    private static final String DEFAULT_TIME_FORMAT = "HH:mm:ss";

    /**
     * ISO日期时间格式
     */
    private static final DateTimeFormatter ISO_DATE_TIME_FORMATTER = new DateTimeFormatterBuilder()
            .parseCaseInsensitive()
            .append(DateTimeFormatter.ISO_LOCAL_DATE_TIME)
            .optionalStart()
            .appendOffset("+HH:MM", "Z")
            .optionalEnd()
            .toFormatter();

    /**
     * 系统默认时区
     */
    private static final ZoneId ZONE_ID = ZoneId.systemDefault();

    /**
     * 自定义LocalDateTime反序列化器类
     */
    public static class CustomLocalDateTimeDeserializer extends LocalDateTimeDeserializer {
        private static final long serialVersionUID = 1L;

        public CustomLocalDateTimeDeserializer(DateTimeFormatter formatter) {
            super(formatter);
        }

        @Override
        public LocalDateTime deserialize(JsonParser parser, DeserializationContext context) throws IOException {
            String text = parser.getText().trim();

            // 首先尝试使用默认格式
            try {
                return LocalDateTime.parse(text, DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_FORMAT));
            } catch (Exception e) {
                // 处理ISO格式带Z的情况
                try {
                    if (text.endsWith("Z")) {
                        // 将UTC时间转换为系统默认时区
                        ZonedDateTime zonedDateTime = ZonedDateTime.parse(text);
                        return zonedDateTime.withZoneSameInstant(ZONE_ID).toLocalDateTime();
                    } else if (text.contains("+") || text.contains("-")) {
                        // 处理带有明确时区的ISO格式
                        ZonedDateTime zonedDateTime = ZonedDateTime.parse(text, ISO_DATE_TIME_FORMATTER);
                        return zonedDateTime.withZoneSameInstant(ZONE_ID).toLocalDateTime();
                    } else {
                        // 尝试作为基本ISO格式解析
                        return LocalDateTime.parse(text);
                    }
                } catch (Exception ignored) {
                    // 继续尝试其他格式或报错
                }
            }

            // 如果所有尝试都失败，抛出异常
            throw new RuntimeException("无法解析日期时间: " + text);
        }
    }

    /**
     * 配置ObjectMapper
     *
     * @return ObjectMapper
     */
    @Bean
    @Primary
    @Order(1)
    public ObjectMapper objectMapper() {
        ObjectMapper objectMapper = new ObjectMapper();

        // 设置时区
        objectMapper.setTimeZone(TimeZone.getTimeZone(ZONE_ID));
        // 设置地区
        objectMapper.setLocale(Locale.CHINA);

        // 设置序列化和反序列化特性
        objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        objectMapper.configure(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE, true);

        // 注册JavaTimeModule，处理Java 8日期/时间类型
        JavaTimeModule javaTimeModule = new JavaTimeModule();

        // 使用自定义的LocalDateTime反序列化器
        javaTimeModule.addDeserializer(
                LocalDateTime.class,
                new CustomLocalDateTimeDeserializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_FORMAT)));

        // 添加LocalDateTime序列化器
        javaTimeModule.addSerializer(
                LocalDateTime.class,
                new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_FORMAT)));

        // 添加LocalDate序列化和反序列化器
        javaTimeModule.addSerializer(
                LocalDate.class,
                new LocalDateSerializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMAT)));
        javaTimeModule.addDeserializer(
                LocalDate.class,
                new LocalDateDeserializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMAT)));

        // 添加LocalTime序列化和反序列化器
        javaTimeModule.addSerializer(
                LocalTime.class,
                new LocalTimeSerializer(DateTimeFormatter.ofPattern(DEFAULT_TIME_FORMAT)));
        javaTimeModule.addDeserializer(
                LocalTime.class,
                new LocalTimeDeserializer(DateTimeFormatter.ofPattern(DEFAULT_TIME_FORMAT)));

        // 注册模块
        objectMapper.registerModule(javaTimeModule);

        // 自动查找并注册所有模块
        objectMapper.findAndRegisterModules();

        return objectMapper;
    }

    /**
     * 自定义Jackson2ObjectMapperBuilder
     *
     * @return Jackson2ObjectMapperBuilderCustomizer
     */
    @Bean
    @Order(1)
    public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
        return builder -> {
            // 设置时区
            builder.timeZone(TimeZone.getTimeZone(ZONE_ID));
            // 设置地区
            builder.locale(Locale.CHINA);

            // 设置Java 8日期/时间格式
            builder.simpleDateFormat(DEFAULT_DATE_TIME_FORMAT);

            // 设置序列化和反序列化特性
            builder.featuresToDisable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
            builder.featuresToDisable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
            builder.featuresToEnable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE);

            // 添加序列化器
            builder.serializers(
                    new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_FORMAT)),
                    new LocalDateSerializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMAT)),
                    new LocalTimeSerializer(DateTimeFormatter.ofPattern(DEFAULT_TIME_FORMAT)));

            // 添加我们的自定义反序列化器
            builder.deserializers(
                    new CustomLocalDateTimeDeserializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_FORMAT)));
        };
    }
}